
package com.eltonkent.ui.tasks;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;

import android.content.Context;
import android.content.SharedPreferences;

import com.eltonkent.db.CredentialTable;
import com.eltonkent.db.FolderListTable;
import com.eltonkent.db.SafeEntryTable;
import com.eltonkent.ui.ApplicationConstants;
import com.eltonkent.ui.ProgressListener;
import com.eltonkent.util.DateUtil;

public class BackupTask extends Thread
{
	private Context context;
	private ProgressListener listener;
	private SharedPreferences prefs;

	public BackupTask(Context context, ProgressListener listener, SharedPreferences prefs)
	{
		this.context = context;
		this.listener = listener;
		this.prefs = prefs;
	}

	File currentBackupFile;

	public void run()
	{
		listener.setProgressStatus(0);
		File appDir = new File(ApplicationConstants.BACK_UP_PATH);
		if(!appDir.exists())
		{
			appDir.mkdir();
		}
		String currentFileName = String.valueOf(System.currentTimeMillis());
		currentBackupFile = new File(ApplicationConstants.BACK_UP_PATH + currentFileName);
		FileOutputStream fos = null;
		DataOutputStream dos = null;
		try
		{
			fos = new FileOutputStream(currentBackupFile);
			dos = new DataOutputStream(fos);
			/* backup password */
			CredentialTable password = new CredentialTable(context);
			password.serialize(dos);
			dos.flush();
			listener.setProgressStatus(10);

			/* backup folders */
			FolderListTable folderTbl = new FolderListTable(context);
			folderTbl.serialize(dos);
			dos.flush();
			listener.setProgressStatus(25);
			/* backup entries */
			SafeEntryTable entries = new SafeEntryTable(context);
			entries.serialize(dos);
			dos.flush();
			listener.setProgressStatus(80);
			File oldFile = new File(ApplicationConstants.BACK_UP_PATH
					+ ApplicationConstants.BACK_UP_FILENAME);
			if(oldFile.exists())
			{
				oldFile.delete();
			}
			currentBackupFile.renameTo(oldFile);
			SharedPreferences.Editor editor = prefs.edit();
			editor.putString(ApplicationConstants.PREF_BACKUP_DATE, DateUtil.getFormattedDate(new Date(
					System.currentTimeMillis())));
			editor.commit();
			listener.operationCompleted(false);
		} catch(FileNotFoundException e1)
		{
			e1.printStackTrace();
		} catch(IOException e2)
		{
			e2.printStackTrace();
		} finally
		{
			try
			{
				dos.close();
				fos.close();
			} catch(IOException e)
			{
				e.printStackTrace();
			}
		}
	}
	/**
	 * backup structure 1. user password. 2.all the folders 3.
	 * 
	 */
}
